﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using XYAC.Framework.MonitorTireMaterialManual.Entities;
using XYAC.Framework.MonitorTireMaterialManual.Extensions;
using XYAC.Framework.MonitorTireMaterialManual.IServices;

namespace XYAC.Framework.MonitorTireMaterialManual.ViewModels
{
    /// <summary>
    /// 设备映射管理视图模型
    /// </summary>
    public partial class EquipmentMappingViewModel : ViewModelBase
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="provider"> 服务提供者</param>
        /// <param name="logger"> 日志记录器</param>
        /// <param name="options"> 配置信息</param>
        public EquipmentMappingViewModel(IServiceProvider provider, ILogger<EquipmentMappingViewModel> logger, IOptionsMonitor<AppConfig> options)
        {
            this.Provider = provider;
            this.Logger = logger;
            this.AppConfig = options;
        }
        #region Fields
        /// <summary>
        /// 所有设备类型
        /// </summary>
        [ObservableProperty]
        private IEnumerable<EqpTypeViewModel> _allEqpTypes = new List<EqpTypeViewModel>()
        {
            new EqpTypeViewModel{ EqpType="胎面",TypeId="1"},
            new EqpTypeViewModel{ EqpType="胎侧",TypeId="2"},
            new EqpTypeViewModel{ EqpType="三角胶",TypeId="3"},
        };
        /// <summary>
        /// 当前表格选中的设备映射
        /// </summary>
        [ObservableProperty]
        private EquipmentMapping currentBindingEqp;
        /// <summary>
        /// 所有设备映射
        /// </summary>
        [ObservableProperty]
        private IEnumerable<EquipmentMapping> allEqps;
        /// <summary>
        /// 机台编号
        /// </summary>
        [ObservableProperty]
        private string eqpNo;

        /// <summary>
        /// 机台名称
        /// </summary>
        [ObservableProperty]
        private string eqpName;

        /// <summary>
        /// 机台类型
        /// </summary>
        [ObservableProperty]
        private EqpTypeViewModel eqpType;
        #endregion


        #region Attribute
        /// <summary>
        /// 服务提供者
        /// </summary>
        public IServiceProvider Provider { get; }
        /// <summary>
        /// 日志记录器
        /// </summary>
        public ILogger<EquipmentMappingViewModel> Logger { get; }
        /// <summary>
        /// 配置信息
        /// </summary>
        public IOptionsMonitor<AppConfig> AppConfig { get; }
        #endregion

        /// <summary>
        /// 刷新设备映射
        /// </summary>
        [RelayCommand]
        internal void Refersh()
        {

            using (var scope = Provider.CreateScope())
            {
                try
                {
                    var context = scope.ServiceProvider.GetService<ILocalDataService>();
                    var result = context.GetAll<EquipmentMapping>();
                    this.AllEqps = result;
                }
                catch (Exception)
                {
                    MessageBox.Show("查询所有设备映射失败，请检查数据库连接是否正常");
                }

            }
        }


        /// <summary>
        /// 新增设备
        /// </summary>
        [RelayCommand]
        private void AddEquipment()
        {
            using (var scope = Provider.CreateScope())
            {
                try
                {
                    var service = scope.ServiceProvider.GetService<ILocalDataService>();
                    var existsEqp = service.GetAll<EquipmentMapping>(T => T.EqpNo == EqpNo).FirstOrDefault();
                    if (existsEqp != null)
                    {
                        MessageBox.Show("无法新增设备,已存在相同的机台编号");
                    }
                    else
                    {
                        //此处对EqpNo   EqpName    EqpType做合法校验
                        if (string.IsNullOrEmpty(EqpNo) || string.IsNullOrEmpty(EqpName) || EqpType == null)
                        {
                            MessageBox.Show("设备编号、名称、类型不能为空");
                        }
                        else
                        {
                            var equipmentMapping = new EquipmentMapping()
                            {
                                EqpNo = EqpNo,
                                EqpName = EqpName,
                                EqpType = EqpType.TypeId
                            };
                            var ret = service.Add(equipmentMapping);
                            if (ret)
                            {
                                Refersh();
                                MessageBox.Show("新增设备成功");
                            }
                            else
                            {
                                MessageBox.Show("新增设备失败，请检查数据库连接是否正常");
                            }
                        }

                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("新增设备失败，请检查数据库连接是否正常");
                }

            }
        }

        /// <summary>
        /// 删除设备映射
        /// </summary>
        /// <param name="eqp"></param>
        [RelayCommand]
        private void DeleteEquipment(EquipmentMapping eqp)
        {
            using (var scope = Provider.CreateScope())
            {
                try
                {
                    if (MessageBox.Show("确定删除该设备映射吗？", "删除设备映射", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        var service = scope.ServiceProvider.GetService<ILocalDataService>();
                        bool ret = service.Delete<EquipmentMapping>(eqp.ID);
                        if (ret)
                        {
                            Refersh();
                            MessageBox.Show("删除设备成功");
                        }
                        else
                        {
                            MessageBox.Show("删除设备失败,请检查数据库连接是否正常");
                        }
                    }

                }
                catch (Exception)
                {
                    MessageBox.Show("删除设备失败,请检查数据库连接是否正常");
                }
            }
        }



        /// <summary>
        /// 更新设备映射
        /// </summary>
        /// <param name="eqp"></param>
        [RelayCommand]
        private void UpdateEquipment(EquipmentMapping eqp)
        {
            using (var scope = Provider.CreateScope())
            {
                try
                {
                    var service = scope.ServiceProvider.GetService<ILocalDataService>();
                    var existsEqp = service.GetAll<EquipmentMapping>(T => T.EqpNo == EqpNo && T.ID != eqp.ID).FirstOrDefault();
                    if (existsEqp != null)
                    {
                        MessageBox.Show("无法更新设备,已存在相同的机台编号");
                    }
                    else
                    {
                        //此处对EqpNo   EqpName    EqpType做合法校验
                        if (string.IsNullOrEmpty(EqpNo) || string.IsNullOrEmpty(EqpName) || EqpType == null)
                        {
                            MessageBox.Show("设备编号、名称、类型不能为空");
                        }
                        else
                        {

                            eqp.EqpNo = EqpNo;
                            eqp.EqpName = EqpName;
                            eqp.EqpType = EqpType.TypeId;

                            var ret = service.Update(eqp);
                            if (ret)
                            {
                                Refersh();
                                MessageBox.Show("更新设备成功");
                            }
                            else
                            {
                                MessageBox.Show("更新设备失败,请检查数据库连接是否正常");
                            }
                        }

                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("新增设备失败，请检查数据库连接是否正常");
                }

            }
        }

        [RelayCommand]
        private void SelectedEqpChanged()
        {
            this.EqpNo = this.CurrentBindingEqp?.EqpNo;
            this.EqpName = this.CurrentBindingEqp?.EqpName;
            this.EqpType = this.AllEqpTypes.FirstOrDefault(T => T.TypeId == this.CurrentBindingEqp?.EqpType);
        }
    }
}
